{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9229a396",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "df1=pd.read_csv('5G_F37_0603_0609.csv')\n",
    "df2=pd.read_csv('5G_F37_0610_0616.csv')\n",
    "df3=pd.read_csv('5G_F37_0617_0623.csv')\n",
    "df4=pd.read_csv('5G_F37_0624_0630.csv')\n",
    "df2.head(300)\n",
    "raw1=df1[df1['UserLabel'].isin(['73aa40cab24113bfcef3e4348118c455-2'])]\n",
    "raw2=df2[df2['UserLabel'].isin(['73aa40cab24113bfcef3e4348118c455-2'])]\n",
    "raw3=df3[df3['UserLabel'].isin(['73aa40cab24113bfcef3e4348118c455-2'])]\n",
    "raw4=df4[df4['UserLabel'].isin(['73aa40cab24113bfcef3e4348118c455-2'])]\n",
    "raw=pd.concat([raw1,raw2,raw3,raw4])\n",
    "print(raw)\n",
    "raw=raw.drop(raw.columns[[0, 1,3]], axis=1)\n",
    "print(raw)\n",
    "from matplotlib import pyplot\n",
    "# load dataset\n",
    "dataset = raw\n",
    "values = dataset.values\n",
    "print(dataset.head())\n",
    "# specify columns to plot\n",
    "groups = [0, 1, 2, 3, 4, 5]\n",
    "i = 1\n",
    "# plot each column\n",
    "pyplot.figure()\n",
    "for group in groups:\n",
    "    pyplot.subplot(len(groups), 1, i)\n",
    "    pyplot.plot(values[:, group])\n",
    "    pyplot.title(dataset.columns[group], y=0.5, loc='right')\n",
    "    i += 1\n",
    "pyplot.show()\n",
    "raw.to_csv('prediction.csv',index = False)\n",
    "dataset = pd.read_csv('prediction.csv', header=0, index_col=0)\n",
    "print(dataset)\n",
    "from sklearn.preprocessing import LabelEncoder\n",
    "from sklearn import preprocessing\n",
    "from sklearn.preprocessing import MinMaxScaler\n",
    "from pandas import DataFrame\n",
    "from pandas import concat\n",
    "\n",
    "\n",
    "# convert series to supervised learning\n",
    "def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):\n",
    "    n_vars = 1 if type(data) is list else data.shape[1]\n",
    "    df = DataFrame(data)\n",
    "    cols, names = list(), list()\n",
    "    # input sequence (t-n, ... t-1)\n",
    "    for i in range(n_in, 0, -1):\n",
    "        cols.append(df.shift(i))\n",
    "        names += [('var%d(t-%d)' % (j+1, i)) for j in range(n_vars)]\n",
    "    # forecast sequence (t, t+1, ... t+n)\n",
    "    for i in range(0, n_out):\n",
    "        cols.append(df.shift(-i))\n",
    "        if i == 0:\n",
    "            names += [('var%d(t)' % (j+1)) for j in range(n_vars)]\n",
    "        else:\n",
    "            names += [('var%d(t+%d)' % (j+1, i)) for j in range(n_vars)]\n",
    "    # put it all together\n",
    "    agg = concat(cols, axis=1)\n",
    "    agg.columns = names\n",
    "    # drop rows with NaN values\n",
    "    if dropnan:\n",
    "        agg.dropna(inplace=True)\n",
    "    return agg\n",
    "\n",
    "# load dataset\n",
    "dataset = pd.read_csv('prediction.csv', header=0, index_col=0)\n",
    "values = dataset.values\n",
    "\n",
    "# integer encode direction\n",
    "encoder = LabelEncoder()\n",
    "values[:,4] = encoder.fit_transform(values[:,4])\n",
    "# ensure all data is float\n",
    "values = values.astype('float32')\n",
    "# # normalize features\n",
    "# scaler = MinMaxScaler(feature_range=(0, 1))\n",
    "# scaled = scaler.fit_transform(values)\n",
    "# # frame as supervised learning\n",
    "# reframed = series_to_supervised(scaled, 1, 1)\n",
    "# # drop columns we don't want to predict\n",
    "# reframed.drop(reframed.columns[[7,8,9,10,11]], axis=1, inplace=True)\n",
    "# print(reframed.head())\n",
    "import numpy as np\n",
    "# scaler = MinMaxScaler(feature_range=(0, 1))\n",
    "# # print(reframed.iloc[:,-1])\n",
    "# # scaled[:,-1] = scaler.fit_transform(reframed[:,-1])\n",
    "# # frame as supervised learning\n",
    "# reframed = series_to_supervised(scaled, 1, 1)\n",
    "# # drop columns we don't want to predict\n",
    "# reframed.drop(reframed.columns[[7,8,9,10,11]], axis=1, inplace=True)\n",
    "# print(reframed)\n",
    "scaler = MinMaxScaler(feature_range=(0, 1))\n",
    "scaled_x = scaler.fit_transform(values[:,:-1])\n",
    "z=values[:,-1]\n",
    "scaled_y = (z - z.min()) / (z.max()-z.min())   \n",
    "# 将(0,1)间数据scale回原来的范围\n",
    "# scaled_df * (df.max() - df.min()) + df.min()\n",
    "# d = np.hstack([scaled_x,scaled_y])\n",
    "scaled=np.column_stack([scaled_x, scaled_y])\n",
    "\n",
    "# frame as supervised learning\n",
    "reframed = series_to_supervised(scaled, 1, 1)\n",
    "# drop columns we don't want to predict\n",
    "reframed.drop(reframed.columns[[7,8,9,10,11]], axis=1, inplace=True)\n",
    "print(reframed.head())\n",
    "print(scaled.shape)\n",
    "# split into train and test sets\n",
    "values = reframed.values\n",
    "n_train_hours = 21*24-1\n",
    "train = values[:n_train_hours, :]\n",
    "test = values[n_train_hours:, :]\n",
    "train_X, train_y = train[:, :-1], train[:, -1]\n",
    "test_X, test_y = test[:, :-1], test[:, -1]\n",
    "pre_X=values[:, :-1]\n",
    "# reshape input to be 3D [samples, timesteps, features]\n",
    "train_X = train_X.reshape((train_X.shape[0], 1, train_X.shape[1])) #train_X.shape[0]为行数  train_X.shape[1]为列数\n",
    "test_X = test_X.reshape((test_X.shape[0], 1, test_X.shape[1]))\n",
    "pre_X = pre_X.reshape((pre_X.shape[0], 1, pre_X.shape[1]))\n",
    "print(train_X.shape, train_y.shape, test_X.shape, test_y.shape)\n",
    "from keras.models import Sequential\n",
    "from keras.layers.recurrent import LSTM\n",
    "from keras.layers import Activation, Dense\n",
    "import matplotlib.pyplot as plt\n",
    "# design network\n",
    "model = Sequential()\n",
    "model.add(LSTM(50, input_shape=(train_X.shape[1], train_X.shape[2])))\n",
    "model.add(Dense(1))\n",
    "model.compile(loss='mae', optimizer='adam')\n",
    "# fit network\n",
    "history = model.fit(train_X, train_y, epochs=1000, batch_size=72, validation_data=(test_X, test_y), verbose=2, shuffle=False)\n",
    "# plot history\n",
    "pyplot.plot(history.history['loss'], label='train')\n",
    "pyplot.plot(history.history['val_loss'], label='test')\n",
    "train_predict = model.predict(test_X)\n",
    "print(len(train_predict))\n",
    "plt.figure(figsize=(24,8))\n",
    "train_predict = model.predict(train_X)\n",
    "test_predict = model.predict(test_X)\n",
    "plt.plot(values[:, -1], c='b')\n",
    "plt.plot([x for x in train_predict], c='g')\n",
    "# plt.plot([None for _ in train_predict], c='y')\n",
    "plt.plot([None for _ in train_predict]  + [x for x in test_predict], c='r')\n",
    "plt.show()\n",
    "print(len(pre))\n",
    "yuan_guiyihua=values[:, -1] * (z.max() - z.min()) + z.min()\n",
    "pre_fanguiyihua=pre * (z.max() - z.min()) + z.min()\n",
    "plt.plot(yuan_guiyihua, c='b')\n",
    "plt.plot([None for _ in yuan_guiyihua]+[x for x in pre_fanguiyihua], c='y')\n",
    "# # plt.plot([None for _ in train_predict]  + [None for x in test_predict] + [x for x in pre], c='g')\n",
    "plt.show()\n",
    "print(values)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "py37",
   "language": "python",
   "name": "py37"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
